# coding:utf-8
# 数据可视化

from mpl_toolkits.mplot3d import Axes3D
from matplotlib.colors import LogNorm
import matplotlib.pyplot as plt
from utils import right_shift
import numpy as np
import math

def create_file_name(title,bit_length,m,p_type,extra_info):
    pass




def four_plot(a_array, b_array,m,title,p_type):

    axes = plt.subplot(221)
    print axes



    plt.subplot(222)


    plt.subplot(223)


    plt.subplot(224)




def plot_compare(a_array,b_array,m,title,p_type):
    """
    参数: 
    输出: 
    描述: 
    """
    bins1 = len(np.arange(min(a_array), max(a_array)+2,1))
    bins2 = len(np.arange(min(b_array), max(b_array)+2,1))
    y1,binEdges1 = np.histogram(a_array, bins=bins1)
    y2,binEdges2 = np.histogram(b_array, bins=bins2)
    if p_type == "p":
        x_lim = (0,m+1)
        plt.xlabel("p")
    elif p_type == "q":
        x_lim = (0,m/2+1)
        plt.xlabel("q")
    
    y1_n = np.zeros(m+1,dtype=int)
    y2_n = np.zeros(m+1,dtype=int)

    for (a,b) in zip(y1,binEdges1):
        y1_n[int(math.ceil(b))] = a

    for (a,b) in zip(y2,binEdges2):
        y2_n[int(math.ceil(b))] = a
    
    y1_n = y1_n - y2_n
    title = title+"  m=%s_%s"%(m,p_type)
    plt.title(title)
    plt.bar(xrange(0,m+1),y1_n,align='center')
    plt.plot()
    plt.savefig("./Result/%s_compare" % title +".png")
    plt.close()


def plot_1dp_figure(r_array,m,title="house",bit_length=0,compare=False):


    bins = len(np.arange(min(r_array), max(r_array)+1,1)) 
    y,binEdges = np.histogram(r_array, bins=bins)
    p_max_index = y.argmax()
    p_count_max = y.max()

    right = 10*m/11
    top = p_count_max
    
    p_max_p = math.ceil(binEdges[p_max_index])
    # print y,binEdges
    bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
    title = title+"  m=%s p_count_max=%s(p=%s)"%(m,y[p_max_index],p_max_p)

    top_text = "m:%s\np_count_max:%s\np:%s\nbins:%s" %(m,y[p_max_index],p_max_p,len(binEdges)-1)
    plt.text(right,top, top_text,
        horizontalalignment='right',
        verticalalignment='top',)
    # plt.text(100, y[p_max_index], 'm=1 \np_count_max=10', style='italic',bbox={'alpha':0, 'pad':10})
    plt.title(title)
    plt.xlim(0,m)
    plt.xlabel("p")
    plt.ylabel("count") 
    plt.bar(bincenters,y,align='center')
    plt.plot()
    plt.savefig("./Result/length=%s_%s_1dp" % (bit_length,title) +".png")
    plt.close()

    plt.title(title)
    plt.xlabel("p")
    plt.ylabel("count") 
    plt.bar(bincenters,y,align='center')
    plt.plot()
    plt.savefig("./Result/length=%s_%s_1dp_no_limit" % (bit_length,title) +".png")
    plt.close()

def plot_1dq_figure(r_array,m,title="house",compare=False,):
    
    bins = len(np.arange(min(r_array), max(r_array)+1,1))
    y,binEdges = np.histogram(r_array, bins=bins)
    p_max_index = y.argmax()
    p_count_max = y.max()
    p_max_p = math.ceil(binEdges[p_max_index])
    right = 99*m/100/2
    top = p_count_max
    title = title+"  m=%s q_count_max=%s(q=%s)"%(m,y[p_max_index],p_max_p)
    top_text = "m:%s\nq_count_max:%s\nq:%s\nbins:%s" %(m,y[p_max_index],p_max_p,len(binEdges)-1)
    plt.text(right,top, top_text,
        horizontalalignment='right',
        verticalalignment='top',)
    # print y,binEdges
    bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
    plt.title(title)
    plt.xlim(0,m/2)
    plt.xlabel("q")
    plt.ylabel("count") 
    plt.bar(bincenters,y,align='center')
    plt.plot()
    plt.savefig("./Result/%s _1dq" % title +".png")
    plt.close()

def plot_2dp_figure(x_array,y_array,title="house",bit_length=0):
    """
    参数: 
    输出: 
    描述: 
    """
    t = np.arange(min(x_array), max(y_array)+1,1)
    plt.hist2d(x_array,y_array,bins=t,norm=LogNorm())
    # plt.axis([x_range[0],x_range[1], y_range[0], y_range[1]])
    x_lim = (0,m)
    y_lim = (0,m/2)
    plt.xlim(x_lim)
    plt.ylim(y_lim)
    title = plt.title(title+"  m=%s"%m)
    plt.title()
    plt.xlabel("pi")
    plt.ylabel("pi+1")
    plt.colorbar()
    plt.plot()
    plt.savefig("./Result/bit_length=%s_%s_2dp" % (bit_length,title) +".png")
    plt.close()


    title = plt.title(title+"  m=%s"%m)
    plt.title()
    plt.xlabel("pi")
    plt.ylabel("pi+1")
    plt.colorbar()
    plt.plot()
    plt.savefig("./Result/bit_length=%s_%s_2dp_no_limit" % (bit_length,title) +".png")
    plt.close()





def hist2d_plot(x_array, y_array,m,p_type,title="",bit_length=0):
    """
        类似于热力图的
        x_array,y_array是 坐标组 
        x_range, y_range是图像坐标最大值参数类型是(min,max)

    """
    title = title+"  _m=%s_%s"% (m,p_type)
    hist, xedges, yedges = np.histogram2d(x_array,y_array)
    t = np.arange(min(y_array), max(x_array)+2,1)
    if p_type == "2dp":
        x_lim = y_lim = (0,m+1)
        plt.xlabel("pi")
        plt.ylabel("pi+1")
        bins = [m,m]
    elif p_type == "2dq":
        x_lim = y_lim = (0,m/2 + 1)
        plt.xlabel("qi")
        plt.ylabel("qi+1")
        bins = [m/2,m/2]
    elif p_type == "2dpq":
        x_lim = (0,m +1)
        y_lim = (0,m/2 + 1)
        plt.xlabel("p")
        plt.ylabel("q")
        bins = [m,m/2 + 1]
    print np.amax(hist)
    # plt.axis([x_range[0],x_range[1], y_range[0], y_range[1]])
    plt.hist2d(x_array,y_array,bins=t,norm=LogNorm())
    plt.xlim(x_lim)
    plt.ylim(y_lim)
    plt.title(title)
    plt.colorbar()
    plt.plot()
    plt.savefig("./Result/length=%s__"%bit_length+ title +".png")
    plt.close()

    plt.hist2d(x_array,y_array,bins=t,norm=LogNorm())
    plt.title(title)
    plt.colorbar()
    plt.plot()
    plt.savefig("./Result/length=%s__"%bit_length+ title +"_no_limit.png")
    plt.close()


def hist2d_plot_three_plot_type1(p_array, q_array, title):
    """
        类似热力图的
        说明：这个图主要是由三个显示图示，p错位坐标图，q错位坐标图，p&q坐标图
    """

    fig, axes = plt.subplots(nrows=2, ncols=2)
    axe0,axe1,axe2,axe3 = axes.flat
    axe0.set_title(u"P")
    # axe0.set_title(u"P projection")
    axe1.set_title(u"Q")
    # axe1.set_title(u"Q projection")
    axe2.set_title(u"P&Q")

    # p错位一下
    t = np.arange(min(p_array), max(p_array)+1,1)
    p_array_o = right_shift(p_array,1)
    axe0.hist2d(p_array, p_array_o,bins=t,norm=LogNorm())
    # axe0.hist2d(p_array, p_array_o,15,norm=LogNorm())

    # p 投影



    # q错位一下
    t = np.arange(min(p_array), max(p_array)+1,1)
    q_array_o = right_shift(q_array,1)
    # axe1.hist2d(q_array, q_array_o, bins=np.arange(min(q_array), max(q_array)+1,1),norm=LogNorm())
    axe1.hist2d(q_array, q_array_o,bins=t,norm=LogNorm())
            
    # q 投影 



    # P&Q
    # axe2.hist2d(p_array, q_array, bins=np.arange(min(q_array), max(q_array)+1,1),norm=LogNorm())
    t = np.arange(min(p_array), max(p_array)+2,1)
    axe2.hist2d(p_array, q_array,bins=t,norm=LogNorm())
    # axe0.colorbar()
    plt.show()


from subsector import subsector_type1
from copy import copy
def main():
    """

    """
    size = 32
    x_range=(0,size)
    y_range = (0,size)
    p_array=[]
    q_array=[]

    r_string = open("d:/VLRC4_p=14_q=2.txt","r").read()

    subsection = subsector_type1(r_string,size)
    for coordinate in subsection:
        if coordinate[0] < coordinate[1]:
            (p, q) = process_type3(r_string[coordinate[0]:coordinate[1]+1])
            # pdb.set_trace()
            p_array.append(copy(p))
            q_array.append(copy(q))
    # hist2d_plot(q_array,p_array, x_range, y_range,"house")
    # print p_array
    # print q_array
    hist2d_plot_three_plot_type1(p_array,q_array,"")

if __name__ == '__main__':
    main()